package cn.datawin.spider.seletor;

import java.util.ArrayList;
import java.util.List;

import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONPath;

/**
 * @author panmg
 * @since 0.5.2
 */
public abstract class AbstractSelectable implements Selectable {

    protected abstract Elements getSourceTexts();

    @Override
    public Selectable css(String selector) {
        return $(selector);
    }

    @Override
    public List<String> all() {
    	List<String> list = new ArrayList<String>();
    	for(Element e: getSourceTexts()){
    		list.add(e.html());
    	}
        return list;
    }

    public List<Element> allele() {
    	List<Element> list = new ArrayList<Element>();
    	for(Element e: getSourceTexts()){
    		list.add(e);
    	}
        return list;
    }
    
    @Override
    public String get() {
        if (all().size()>0) {
            return all().get(0);
        } else {
            return null;
        }
    }
    
    @Override
    public Element get(int num) {
        if (allele().size()>num) {
            return allele().get(num);
        } else {
            return null;
        }
    }

    public String getFirstSourceText() {
        if (getSourceTexts() != null && getSourceTexts().size() > 0) {
            return all().get(0);
        }
        return null;
    }

    @Override
    public boolean match() {
        return getSourceTexts() != null && getSourceTexts().size() > 0;
    }
    

    @Override
    public List<String> jsonPathList(String text, String path) {
    	Object obj = JSONPath.eval(JSON.parse(text), path);
    	if(obj instanceof List){
    		return (List<String>)obj;
    	}
    	List<String> list = new ArrayList<String>();
    	if(obj == null) return list;
    	list.add(obj.toString());
    	return  list;
    }
}
